<?php

namespace app\api\controller\User;

use think\Controller;

use PHPMailer;

class Base extends Controller
{
    public function __construct()
    {
        parent::__construct();

        $this->UserModel = model('User.User');
    }
    public function index()
    {
        return '网站升级~';
    }

    public function login()
    {
        $email = $this->request->param('email', '');

        $password = $this->request->param('password', '');

        $User = $this->UserModel->where('email', $email)->find();

        if (!$User) {
            $this->error('用户不存在，请重新输入');
            exit;
        }

        $salt = $User['salt'];

        $pass = md5($password . $salt);

        if ($pass != $User['password']) {
            $this->error('密码错误，请重新输入');
            exit;
        }
        $data = [
            'id' => $User['id'],
            'email' => $User['email'],
            'nickname' => $User['nickname'],
            'sex' => $User['sex'],
            'avatar' => $User['avatar_cdn'],
            'province' => $User['province'],
            'city' => $User['city'],
            'district' => $User['district'],
            'createtime' => $User['createtime'],
            'content' => $User['content'],
            'vip' => $User['vip'],
            'auth' => $User['auth'],
            'point' => $User['point'],
            'cover_cdn' => $User['cover_cdn'],
            'region' => $User['region']

        ];


        $this->success('登录成功', '/user/base/index', $data);
    }

    public function check()
    {
        $id = $this->request->param('id', 0);

        $User = $this->UserModel->find($id);

        if (!$User) {
            $this->error('非法登录');
            exit;
        }

        $data = [
            'id' => $User['id'],
            'email' => $User['email'],
            'nickname' => $User['nickname'],
            'sex' => $User['sex'],
            'avatar' => $User['avatar_cdn'],
            'province' => $User['province'],
            'city' => $User['city'],
            'district' => $User['district'],
            'createtime' => $User['createtime'],
            'content' => $User['content'],
            'vip' => $User['vip'],
            'auth' => $User['auth'],
            'point' => $User['point'],
            'cover' => $User['cover_cdn'],
            'region' => $User['region']
        ];


        $this->success('验证成功', null, $data);
    }

    public function profile()
    {
        $userid = $this->request->param('id', 0);

        $params = $this->request->param();

        $User = $this->UserModel->find($userid);

        if (!$User) {
            $this->error('用户不存在');
            exit;
        }

        $data = [
            'id' => $userid,
            'nickname' => $params['nickname'],
            'sex' => $params['sex'],
            'content' => $params['content'],
            'province' => $params['province'],
            'city' => $params['city'],
            'district' => $params['district']
        ];

        if (!empty($params['password'])) {
            $salt = build_ranstr();

            $password = md5($params['password'] . $salt);

            $data['password'] = $password;
        }

        if (!empty($_FILES['avatar']) && $_FILES['avatar']['size'] > 0) {
            $avatar = upload('avatar');

            // halt($avatar);
            if ($avatar === FALSE) {
                $this->error('图像上传失败');
                exit;
            }

            $data['avatar'] = $avatar;
        }

        if (!empty($_FILES['cover']) && $_FILES['cover']['size'] > 0) {
            $cover = upload('cover');

            // halt($cover);
            if ($cover === FALSE) {
                $this->error('背景上传失败');
                exit;
            }

            $data['cover'] = $cover;
        }

        $result = $this->UserModel->isUpdate(true)->save($data);

        if ($result === FALSE) {
            @is_file(ROOT_PATH . 'public' . DS . $avatar) && @unlink(ROOT_PATH . 'public' . DS . $avatar);
            @is_file(ROOT_PATH . 'public' . DS . $cover) && @unlink(ROOT_PATH . 'public' . DS . $cover);

            $this->error('修改失败');
            exit;
        } else {
            if (!empty($_FILES['avatar']) && $_FILES['avatar']['size'] > 0) {

                @is_file(ROOT_PATH . 'public' . DS . $User['avatar']) && @unlink(ROOT_PATH . 'public' . DS . $User['avatar']);
            }
            if (!empty($_FILES['cover']) && $_FILES['cover']['size'] > 0) {
                @is_file(ROOT_PATH . 'public' . DS . $User['cover']) && @unlink(ROOT_PATH . 'public' . DS . $User['cover']);
            }

            $UserData = $this->UserModel->find($userid);

            $data = [
                'id' => $UserData['id'],
                'email' => $UserData['email'],
                'nickname' => $UserData['nickname'],
                'sex' => $UserData['sex'],
                'avatar' => $UserData['avatar_cdn'],
                'province' => $UserData['province'],
                'city' => $UserData['city'],
                'district' => $UserData['district'],
                'createtime' => $UserData['createtime'],
                'content' => $UserData['content'],
                'vip' => $UserData['vip'],
                'auth' => $UserData['auth'],
                'point' => $UserData['point'],
                'cover' => $UserData['cover_cdn'],
                'region' => $UserData['region']
            ];

            $this->success('更新成功', null, $data);
        }
    }
    //发送邮箱验证码
    public function email()
    {
        if ($this->request->isPost()) {

            $email = $this->request->param('email', '');

            $userid = $this->request->param('userid', 0);

            $user = $this->UserModel->find($userid);

            if (!$user) {
                $this->error('用户不存在');
                exit;
            }

            require_once(EXTEND_PATH . 'phpmail/class.phpmailer.php');
            // couiazbjizfffjai  => 授权码
            // JYCBYAJWJWDWBDUY
            // 实例化发送邮件类
            $mail = new PHPMailer(true);

            // 启用smtp
            $mail->IsSMTP(true);
            // SMTP服务器 qq => smtp.qq.com
            $mail->Host = "smtp.qq.com";
            // 开启smtp认证
            $mail->SMTPAuth = true;
            // 发送内容支持HTML
            $mail->IsHTML(true);
            // 邮箱用户名 => SMTP账号
            $mail->Username = "1871142580@qq.com";
            // 密码 => 授权码
            $mail->Password = "xvlpjiwrmhfiidfa";
            // 设置SMTP服务端口 上线后需要服务器开启这个端口 
            $mail->Port = 465;

            $mail->Timeout = 60;

            // ssl协议
            $mail->SMTPSecure = 'ssl';

            // 发件人
            $mail->From = "1871142580@qq.com";

            // 发件人名称
            $mail->FromName = "ask论坛";

            //回复人
            $mail->AddReplyTo("1871142580@qq.com", "ask论坛");

            // 收件人的邮箱和名称
            $mail->AddAddress($email, $user['nickname']);
            // 邮件主题 => 标题
            $mail->Subject  = "ask论坛激活认证";

            //设置多少个字符换行 80字符
            $mail->WordWrap = 50;

            // 生成随机码
            $msg = build_ranstr();

            session('sms', $msg);

            // 发送内容
            // $mail->Body = $msg;
            $mail->MsgHTML($msg);

            // 发送内容支持HTML
            $mail->IsHTML(true);

            // 发送
            $res = $mail->Send();

            if ($res === FALSE) {
                $this->error('邮件发送失败');
                exit;
            } else {
                $this->success('邮件发送成功');
                exit;
            }
        }
    }
    //邮箱验证
    public function emailcheck()
    {
        $sms = $this->request->param('sms', '');
        // echo $sms;

        $check = session('sms');
        // echo $check;

        $userid = $this->request->param('userid', 0);

        $user = $this->UserModel->find($userid);

        if (!$sms) {
            $this->error('验证码不能为空');
            exit;
        }

        if (!$user) {
            $this->error('用户不存在');
            exit;
        }



        if (strtolower($sms) != strtolower($check)) {
            $this->error('验证码错误');
            exit;
        }

        $result = $this->UserModel->where(['id' => $userid])->update(['auth' => 1]);

        if ($result === FALSE) {
            $this->error('验证失败');
            exit;
        } else {
            $this->success('验证成功');
            exit;
        }
    }

    //注册
    public function register()
    {
        // 接收邮箱
        $email = $this->request->param('email', '');
        // 接收昵称
        $nickname = $this->request->param('nickname', '');
        // 接收密码
        $password = $this->request->param('password', '');
        // 接收确认密码
        $repass = $this->request->param('repass', '');

        //通过email到用户表查询， 如果有，则提示已存在
        $User = $this->UserModel->where('email', $email)->find();

        if ($User) {
            $this->error('用户已存在，请重新输入');
            exit;
        }
        // 生成10位随机字符串
        $salt = build_ranstr(10);

        // 判断密码和确认密码是否一致
        if ($password != $repass) {
            $this->error('密码不一致，请重新输入');
            exit;
        }

        // 把密码加密
        $pass = md5($password . $salt);

        // 封装插入数据的数组
        $data = [
            'email' => $email,
            'password' => $pass,
            'salt' => $salt,
            'nickname' => $nickname,
        ];

        // 插入数据表
        $result = $this->UserModel->save($data);

        // 判断数值和类型是否一致
        if ($result === FALSE) {

            $this->error($this->UserModel->getError());
            exit;
        } else {
            $this->success('注册成功', '/user/base/index', $data);
            exit;
        }
    }

    // 微信上传图片demo的接口
    public function avatar()
    {
        if($this->request->isPost())
        {
            // halt($this->request->file('avatar'));

            $userid = $this->request->param('userid',0);
            // 查询这条信息是否存在
            $user = $this->UserModel->find($userid);

            if(!$user)
            {
                return json(['code' => 0,'msg' => '用户不存在']);
            }

            $avatar = upload('avatar');

            if($avatar === FALSE)
            {
                return json(['code' => 0, 'msg' => '头像上传失败']);
            }

            $data = [
                'id' => $userid,
                'avatar' => $avatar,
            ];
            // 判断是否有操作再进行保存到模型
            $result = $this->UserModel->isUpdate(true)->save($data);
            
            if($result === FALSE)
            {
                @is_file(ROOT_PATH . 'public' . DS . $avatar) && @unlink(ROOT_PATH . 'public' . DS . $avatar);
                return json(['code' => 0, 'msg' => '更新头像失败']);
            }else{
                @is_file(ROOT_PATH . 'public' . DS . $user['avatar']) && @unlink(ROOT_PATH . 'public' . DS . $user['avatar']);
                return json(['code' => 1, 'msg' => '更新头像成功']);
            }


        }
    }

    // 微信获取openid
    public function auth()
    {
        if($this->request->isPost())
        {
            $code = $this->request->param('code','');

            if(!$code)
            {
                return json(['code' => 0,'msg' => '授权失败']);
            }

            $ApiUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=wxccc83c3f36033dec&secret=d9ecf9e2a5e6ec74f93485cdd9173e9e&js_code=$code&grant_type=authorization_code";

            $result = file_get_contents($ApiUrl);

            $result = json_decode($result,true);

            $openid = isset($result['openid']) ? $result['openid'] : '';

            if(!$openid)
            {
                return json(['code' => 0,'msg' => '获取凭证失败']);
            }

            $user = $this->UserModel->where(['openid' => $openid])->find();

            // halt($user);
            if($user === FALSE)
            {
                return json(['code' => 0,'msg' => '登录失败']);
            }else{
                $data = [
                    'id' => $user['id'],
                    'sex' => $user['sex'],
                    'avatar' => $user['avatar_cdn'],
                    'nickname' => $user['nickname'],
                    'content' => $user['content']
                ];

                return json(['code' => 1,'msg' => '登陆成功', 'data' => $data]);
            }
        }
    }
}
